/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { ModalRef } from '@iux/live';
import {
  ProtectedResourceApiService,
  UsersApiService
} from 'app/shared/api/services';
import { CommonConsts } from 'app/shared/consts';
import { DataMapService } from 'app/shared/services';
import { find, isArray, map } from 'lodash';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'aui-resource-modify-user',
  templateUrl: './resource-modify-user.component.html',
  styleUrls: ['./resource-modify-user.component.less']
})
export class ResourceModifyUserComponent implements OnInit {
  resource;
  formGroup: FormGroup;
  userOptions = [];
  MAX_PAGE_SIZE = 500;

  constructor(
    private fb: FormBuilder,
    private modal: ModalRef,
    private dataMapService: DataMapService,
    private usersApiService: UsersApiService,
    private protectedResourceApiService: ProtectedResourceApiService
  ) {}

  ngOnInit(): void {
    this.initFrom();
    this.getUserOptions();
  }

  initFrom() {
    this.formGroup = this.fb.group({
      owned_user: new FormControl('')
    });
    this.formGroup.valueChanges.subscribe(() => this.checkBtnDisabled());
  }

  checkBtnDisabled() {
    this.modal.getInstance().lvOkDisabled = this.formGroup.invalid;
  }

  parseUser(recordsTemp) {
    this.userOptions = map(recordsTemp, item => {
      return {
        ...item,
        key: item.userId,
        value: item.userId,
        label: item.userName,
        isLeaf: true
      };
    });
    if (
      this.resource?.userId &&
      find(this.userOptions, item => item.userId === this.resource?.userId)
    ) {
      this.formGroup.get('owned_user')?.setValue(this.resource?.userId);
    }
  }

  getUserOptions(startPage = CommonConsts.PAGE_START_EXTRA, recordsTemp = []) {
    const filterUser = map(
      this.dataMapService.toArray('defaultRoleName'),
      'value'
    ).filter(v => v !== 'Role_DP_Admin');
    filterUser.push('Role_Device_Manager');
    const params = {
      startIndex: startPage,
      pageSize: this.MAX_PAGE_SIZE,
      filter: JSON.stringify({
        includeRoleList: filterUser
      })
    };
    this.usersApiService.getAllUserUsingGET(params).subscribe(res => {
      if (isArray(res.userList)) {
        recordsTemp = [...recordsTemp, ...res.userList];
      }
      if (
        res.total === 0 ||
        startPage === Math.ceil(res.total / this.MAX_PAGE_SIZE)
      ) {
        this.parseUser(recordsTemp);
        return;
      }
      startPage++;
      this.getUserOptions(startPage, recordsTemp);
    });
  }

  onOk(): Observable<any> {
    const params = {
      resourceId: this.resource?.uuid,
      userId: this.formGroup.get('owned_user')?.value || ''
    };
    if (!this.resource?.userId && !params.userId) {
      return of({});
    }
    return this.protectedResourceApiService.UpdateResourceUser({
      resourceUserObjectReq: params
    });
  }
}
